package com.ruoyi.controller;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Anonymous;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.domain.Ai;
import com.ruoyi.service.IAiService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import static net.sf.jsqlparser.parser.feature.Feature.update;

/**
 * aiController
 * 
 * @author ya
 * @date 2025-05-25
 */
@RestController
@RequestMapping("/ai/ai")
public class AiController extends BaseController
{
    @Autowired
    private IAiService aiService;

    @Autowired
    private FileStorageService fileStorageService;//注入实列

    /**
     * 查询ai列表
     */
    @Anonymous
    @GetMapping("/list")
    public TableDataInfo list(Ai ai)
    {
        startPage();
        List<Ai> list = aiService.selectAiList(ai);
        return getDataTable(list);
    }

    /**
     * 导出ai列表
     */
    @Anonymous
    @Log(title = "ai", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Ai ai)
    {
        List<Ai> list = aiService.selectAiList(ai);
        ExcelUtil<Ai> util = new ExcelUtil<Ai>(Ai.class);
        util.exportExcel(response, list, "ai数据");
    }

    /**
     * 获取ai详细信息
     */
    @Anonymous
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(aiService.selectAiById(id));
    }

    /**
     * 新增ai
     */
    @Anonymous
    @Log(title = "ai", businessType = BusinessType.INSERT)
    @PostMapping("/add/{id}")
    public AjaxResult add(
            @PathVariable Long id,
            @RequestParam(value = "title", required = false) String title,
            @RequestParam(value = "file", required = false) MultipartFile file,
            @RequestParam(value = "date", required = false)
            @DateTimeFormat(pattern = "yyyy-M-d") Date date) {

        try {
            Ai ai = new Ai();
            ai.setId(id);

            // 选择性设置字段
            if (title != null) ai.setTitle(title);
            if (date != null) ai.setDate(date);

            // 处理文件上传
            if (file != null && !file.isEmpty()) {
                String basePath = "aiFiles/";
                String objectName = basePath + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"))
                        + "/" + file.getOriginalFilename();

                FileInfo fileInfo = fileStorageService.of(file)
                        .setPath(objectName)
                        .upload();
                ai.setFile(fileInfo.getUrl());
            }

            // 至少需要有一个有效字段
            if (ai.getTitle() == null && ai.getDate() == null && ai.getFile() == null) {
                return AjaxResult.error("至少需要提交一个有效字段（title/date/file）");
            }

            return toAjax(aiService.insertAi(ai));

        } catch (Exception e) {
            return AjaxResult.error("操作失败: " + e.getMessage());
        }
    }



    /**
     * 修改ai
     */
    @Anonymous
    @Log(title = "ai", businessType = BusinessType.UPDATE)
    @PutMapping("/update/{id}")
    public AjaxResult edit(
            @PathVariable Long id,
            @RequestParam(value = "title", required = false) String title,
            @RequestParam(value = "file", required = false) MultipartFile file,
            @RequestParam(value = "date", required = false)
            @DateTimeFormat(pattern = "yyyy-M-d") Date date) {

        try {
            // 获取现有数据
            Ai existingAi = aiService.selectAiById(id);
            if (existingAi == null) {
                return AjaxResult.error("记录不存在");
            }

            // 创建更新对象
            Ai updateAi = new Ai();
            updateAi.setId(id);

            // 选择性更新字段
            if (title != null) updateAi.setTitle(title);
            if (date != null) updateAi.setDate(date);

            // 处理文件更新
            if (file != null && !file.isEmpty()) {
                String basePath = "aiFiles/";
                String objectName = basePath + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"))
                        + "/" + file.getOriginalFilename();

                FileInfo fileInfo = fileStorageService.of(file)
                        .setPath(objectName)
                        .upload();
                updateAi.setFile(fileInfo.getUrl());
            }


            // 执行部分更新
            return toAjax(aiService.updateAi(updateAi));

        } catch (Exception e) {
            return AjaxResult.error("更新失败: " + e.getMessage());
        }
    }

    @Anonymous
    @Log(title = "ai", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(aiService.deleteAiByIds(ids));
    }
}
